package qrcode;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;

/**
 * @description: 二维码生成器
 * @author: 陈瑞东
 * @create: 2021-07-14 11:14
 */
public class QRCodeGenerator {
    /*
    依赖：
        <dependencies>
            <dependency>
                <groupId>com.google.zxing</groupId>
                <artifactId>core</artifactId>
                <version>3.3.0</version>
            </dependency>
            <dependency>
                <groupId>com.google.zxing</groupId>
                <artifactId>javase</artifactId>
                <version>3.3.0</version>
            </dependency>
        </dependencies>
     */

    public static final int BACKGROUND_WIDTH =500; // 背景板宽度
    public static final int BACKGROUND_HEIGHT =500; // 背景板高度

    /**
     * 根据文本生成二维码
     * @param text 文本
     * @param description 底部描述
     * @param width 二维码宽度
     * @param height 二维码高度
     * @return 二维码图片
     * @throws WriterException
     */
    public static BufferedImage generateQRCodeImage(String text, String description, int width, int height) throws WriterException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        // 设置字符集
        HashMap<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
        // 二维码
        BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

        // 背景板
        BufferedImage background = new BufferedImage(BACKGROUND_WIDTH, BACKGROUND_HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = background.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, BACKGROUND_WIDTH, BACKGROUND_HEIGHT);

        // 将二维码拼接到背景板上
        int qrX = (background.getWidth() - qrImage.getWidth()) / 2;
        int qrY = (background.getHeight() - qrImage.getHeight()) / 2;
        graphics.drawImage(qrImage, qrX, qrY, null);

        // 在二维码下方填写文字
        graphics.setColor(Color.BLACK);
        graphics.setFont(new Font("宋体", Font.BOLD, 20));
        FontMetrics fontMetrics = graphics.getFontMetrics();
        int stringWidth = fontMetrics.stringWidth(description);
        int stringHeight = fontMetrics.getHeight();
        int stringX = (background.getWidth() - stringWidth) / 2;
        int stringY = qrY + qrImage.getHeight();
        graphics.drawString(description, stringX, stringY);

        return background;
    }
}
